package com.example.teacher;

import android.util.Log;

import com.orhanobut.hawk.Hawk;

import org.json.JSONException;
import org.json.JSONObject;
import org.webrtc.IceCandidate;
import org.webrtc.PeerConnection;
import org.webrtc.SessionDescription;

import java.net.URISyntaxException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

/**
 * Created by chao on 2019/1/30.
 */

public class ExaminStatusSocket {
    private static final String TAG = "ExaminStatusSocket";
    private static ExaminStatusSocket instance;
    private String userId;
    private List<String>stringList=new ArrayList<>();
    private List<String>stringKey=new ArrayList<>();
   private List<HashMap<String ,PeerConnection  >>hashMapList=new ArrayList<>();
   private List<PeerConnection>peerConnectionList=new ArrayList<>();
  private  boolean meIsInfirst=false;
    private ExaminStatusSocket(){}
    public static ExaminStatusSocket get() {
        if(instance == null) {
            synchronized (ExaminStatusSocket.class) {
                if(instance == null) {
                    instance = new ExaminStatusSocket();
                }
            }
        }
        return instance;
    }

    private Socket socket;
    private String room = "roomid1";
    private Callback callback;


    private final TrustManager[] trustAll = new TrustManager[]{
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }
    };

    public void init(Callback callback) {
        this.callback = callback;
           /* SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAll, null);
            IO.setDefaultHostnameVerifier((hostname, session) -> true);
            IO.setDefaultSSLContext(sslContext);*/
            IO.Options opts = new IO.Options();
            opts.forceNew = false;
            opts.reconnection = true;
            opts.reconnectionDelay = 2000;      //延迟
            opts.reconnectionDelayMax = 6000;
            opts.reconnectionAttempts = -1;
            opts.timeout = 6000;
            if (socket == null) {
                try {
                    socket = IO.socket("http://42.192.8.62:8011",opts);
                    socket.connect();
                    addHandles();
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }

        if (Hawk.contains("userId")){
            userId=Hawk.get("userId");
        }

        // 其他用户加入通知
            socket.on("startExam", args -> {
                callback.onStartExam();
            });

        // 其他用户加入通知
        socket.on("endExam", args -> {

            callback.onEndExam();
        });


        socket.on("err", args -> {
            Log.d(TAG, "err= " + args[0]);
           // callback.onPeerJoined(String.valueOf(args[1]));
        });

        //主要是收到端对端的消息 进行处理
            socket.on("message", args -> {
                Object arg = args[1];
                if (arg instanceof String) {

                } else if (arg instanceof JSONObject) {
                    Log.d(TAG+"8888", "message " +  Arrays.toString(args));
                    JSONObject data = (JSONObject) arg;
                    JSONObject d = data.optJSONObject("data");
                    String type = d.optString("type");

                  /*  Log.d(TAG+"99", "message " +  d.optString("type"));
                    Log.d(TAG+"99", "message " +  d.optString("sdp"));
                    Log.d(TAG+"99", "message " +  d.optString("account"));*/
                    Log.d("JSONObject===", "bye==" + type);
                }
            });
        }
    //结束考试
    public void endExam() {
        socket.emit("endExam", "roomid1");
    }
    //开始考试
    public void startExam() {
        socket.emit("startExam", "roomid1");
    }
    private  void addHandles() {
        /*
         * 断开连接
         * */
        socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {

                Log.i(TAG, "连接断开");

            }
        });

        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Log.i(TAG, "连接中");


            }
        });

        socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Log.i(TAG, "连接失败=="+args[0].toString()+"===="+ args[0].hashCode());

            }
        });

        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Log.i(TAG, "连接成功");

            }
        });}
    public void destroy() {
        socket.emit("bye", socket.id());
        socket.disconnect();
        socket.close();
        instance = null;
    }

    public interface Callback {
        void onStartExam();
        void onEndExam();
      ;
    }

}
